using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

[System.Serializable]
public class GeneralInfo
{
    public string generalName;     // 将军名称
    public int health;             // 将军生命值
    public bool is_attacking;      // 是否正在战斗
    public bool is_arrive;         // 是否到达目的地
    public int infantryAccount;    // 步兵数量
    public int archerAccount;      // 弓箭手数量
    public int cavalryAccount;     // 骑兵数量
    public string currentPosition; // 当前位置坐标
    public string targetPosition;  // 目标位置坐标
    public string formation;       // 阵型
    public string activity;        // 行为
}

public class Wei_General_Manager : MonoBehaviour
{
    // 单例模式
    public static Wei_General_Manager Instance { get; private set; }

    // 所有魏国将军
    [SerializeField] private XiaHouDun xiaHouDun;
    [SerializeField] private XuHuang xuHuang;

    [SerializeField] private XuChu xuChu;
    // 根据需要添加其他将军

    // 导出频率（秒）
    [SerializeField] private float exportInterval = 5f;

    // 导出路径
    private string exportFolderPath;
    private string exportFilePath;

    void Awake()
    {
        // 实现单例模式
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }

        // 设置导出路径
        exportFolderPath = Path.Combine(Application.dataPath, "Scripts/Wu_test/Wei/Wei_Information");
        exportFilePath = Path.Combine(exportFolderPath, "generalInfo.json");
    }

    void Start()
    {
        // 初始化时查找所有将军组件（如果没有在Inspector中设置）
        if (xiaHouDun == null) xiaHouDun = FindObjectOfType<XiaHouDun>();
        if (xuHuang == null) xuHuang = FindObjectOfType<XuHuang>();
        if (xuChu == null) xuChu = FindObjectOfType<XuChu>();

        // 不再自动启动导出协程，由Wei_Information_Manager控制导出时机
        // StartCoroutine(ExportGeneralsInfoRoutine());

        Debug.Log("魏国将军管理器已初始化，等待统一信息管理器进行导出");
    }

    // 定时导出将军信息的协程
    private IEnumerator ExportGeneralsInfoRoutine()
    {
        while (true)
        {
            ExportGeneralsInfo();
            yield return new WaitForSeconds(exportInterval);
        }
    }

    // 手动触发导出将军信息（已废弃，请使用ExportGeneralsInfoToFile来指定准确的文件路径）
    public void ExportGeneralsInfo()
    {
        Debug.LogWarning("ExportGeneralsInfo方法已废弃，请使用ExportGeneralsInfoToFile方法并指定文件路径。不再生成固定名称的文件。");

        // 不再生成固定名称的文件，而是记录一下当前将军状态
        List<GeneralInfo> generalsInfo = new List<GeneralInfo>();

        // 检查将军状态并记录日志
        if (xiaHouDun != null && xiaHouDun.health > 0)
        {
            Debug.Log($"将军 {xiaHouDun.generalName} 健康值: {xiaHouDun.health}");
        }

        if (xuHuang != null && xuHuang.health > 0)
        {
            Debug.Log($"将军 {xuHuang.generalName} 健康值: {xuHuang.health}");
        }

        if (xuChu != null && xuChu.health > 0)
        {
            Debug.Log($"将军 {xuChu.generalName} 健康值: {xuChu.health}");
        }

        if ((xiaHouDun == null || xiaHouDun.health <= 0) &&
            (xuHuang == null || xuHuang.health <= 0) &&
            (xuChu == null || xuChu.health <= 0))
        {
            Debug.LogWarning("没有存活的魏国将军！");
        }
    }

    // 导出将军信息到指定文件路径
    public void ExportGeneralsInfoToFile(string filePath)
    {
        List<GeneralInfo> generalsInfo = new List<GeneralInfo>();

        // 检查曹操是否存在并添加到将军列表
        Wei_ZhuGong caoCao = FindObjectOfType<Wei_ZhuGong>();
        if (caoCao != null && caoCao.health > 0)
        {
            GeneralInfo info = new GeneralInfo
            {
                generalName = caoCao.generalName,
                health = caoCao.health,
                is_attacking = caoCao.is_attacking,
                is_arrive = caoCao.is_arrive,
                infantryAccount = caoCao.infantryAccount,
                archerAccount = caoCao.archerAccount,
                currentPosition = caoCao.currentPosition,
                cavalryAccount = caoCao.cavalryAccount,
                targetPosition = caoCao.targetPosition,
                formation = caoCao.formation,
                activity = caoCao.activity
            };
            generalsInfo.Add(info);
            Debug.Log($"已添加曹操信息：健康值: {caoCao.health}, 目标: {caoCao.targetPosition}, 活动: {caoCao.activity}");
        }

        // 检查夏侯惇是否存活
        if (xiaHouDun != null && xiaHouDun.health > 0)
        {
            GeneralInfo info = new GeneralInfo
            {
                generalName = xiaHouDun.generalName,
                health = xiaHouDun.health,
                is_attacking = xiaHouDun.is_attacking,
                is_arrive = xiaHouDun.is_arrive,
                infantryAccount = xiaHouDun.infantryAccount,
                archerAccount = xiaHouDun.archerAccount,
                cavalryAccount = xiaHouDun.cavalryAccount,
                currentPosition = xiaHouDun.currentPosition,
                targetPosition = xiaHouDun.targetPosition,
                formation = xiaHouDun.formation,
                activity = xiaHouDun.activity
            };
            generalsInfo.Add(info);
        }

        // 检查徐晃是否存活
        if (xuHuang != null && xuHuang.health > 0)
        {
            GeneralInfo info = new GeneralInfo
            {
                generalName = xuHuang.generalName,
                health = xuHuang.health,
                is_attacking = xuHuang.is_attacking,
                is_arrive = xuHuang.is_arrive,
                infantryAccount = xuHuang.infantryAccount,
                archerAccount = xuHuang.archerAccount,
                cavalryAccount = xuHuang.cavalryAccount,
                currentPosition = xuHuang.currentPosition,
                targetPosition = xuHuang.targetPosition,
                formation = xuHuang.formation,
                activity = xuHuang.activity
            };
            generalsInfo.Add(info);
        }

        // 检查许褚是否存活
        if (xuChu != null && xuChu.health > 0)
        {
            GeneralInfo info = new GeneralInfo
            {
                generalName = xuChu.generalName,
                health = xuChu.health,
                is_attacking = xuChu.is_attacking,
                is_arrive = xuChu.is_arrive,
                infantryAccount = xuChu.infantryAccount,
                archerAccount = xuChu.archerAccount,
                cavalryAccount = xuChu.cavalryAccount,
                currentPosition = xuChu.currentPosition,
                targetPosition = xuChu.targetPosition,
                formation = xuChu.formation,
                activity = xuChu.activity
            };
            generalsInfo.Add(info);
        }

        // 如果没有存活的将军，则输出警告
        if (generalsInfo.Count == 0)
        {
            Debug.LogWarning("没有存活的魏国将军！");
            return;
        }

        // 生成指定路径的JSON文件
        ExportGeneralsList(generalsInfo, filePath);
    }

    // 将将军列表导出为JSON文件
    private void ExportGeneralsList(List<GeneralInfo> generalsInfo, string filePath)
    {
        // 生成JSON字符串
        string json = "[\n";
        for (int i = 0; i < generalsInfo.Count; i++)
        {
            var general = generalsInfo[i];
            json += $"  {{\n";
            json += $"    \"generalName\": \"{general.generalName}\",\n";
            json += $"    \"health\": {general.health},\n";
            json += $"    \"is_attacking\": {general.is_attacking.ToString().ToLower()},\n";
            json += $"    \"is_arrive\": {general.is_arrive.ToString().ToLower()},\n";
            json += $"    \"infantryAccount\": {general.infantryAccount},\n";
            json += $"    \"archerAccount\": {general.archerAccount},\n";
            json += $"    \"cavalryAccount\": {general.cavalryAccount},\n";
            json += $"    \"currentPosition\": \"{general.currentPosition}\",\n";
            json += $"    \"targetPosition\": \"{general.targetPosition}\",\n";
            json += $"    \"formation\": \"{general.formation}\",\n";
            json += $"    \"activity\": \"{general.activity}\"\n";
            json += $"  }}";

            if (i < generalsInfo.Count - 1)
            {
                json += ",\n";
            }
            else
            {
                json += "\n";
            }
        }
        json += "]";

        // 确保目录存在
        Directory.CreateDirectory(Path.GetDirectoryName(filePath));

        // 写入文件
        try
        {
            File.WriteAllText(filePath, json);
            Debug.Log($"成功导出魏国将军信息到: {filePath}");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"导出将军信息时出错: {e.Message}");
        }

        // 刷新Asset数据库以显示新文件
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();
#endif
    }

    // 根据名称获取将军对象
    public GeneralInfo GetGeneralInfoByName(string generalName)
    {
        if (xiaHouDun != null && xiaHouDun.health > 0 && xiaHouDun.generalName == generalName)
        {
            return new GeneralInfo
            {
                generalName = xiaHouDun.generalName,
                health = xiaHouDun.health,
                is_attacking = xiaHouDun.is_attacking,
                is_arrive = xiaHouDun.is_arrive,
                infantryAccount = xiaHouDun.infantryAccount,
                archerAccount = xiaHouDun.archerAccount,
                cavalryAccount = xiaHouDun.cavalryAccount,
                currentPosition = xiaHouDun.currentPosition,
                targetPosition = xiaHouDun.targetPosition,
                formation = xiaHouDun.formation,
                activity = xiaHouDun.activity
            };
        }
        else if (xuHuang != null && xuHuang.health > 0 && xuHuang.generalName == generalName)
        {
            return new GeneralInfo
            {
                generalName = xuHuang.generalName,
                health = xuHuang.health,
                is_attacking = xuHuang.is_attacking,
                is_arrive = xuHuang.is_arrive,
                infantryAccount = xuHuang.infantryAccount,
                archerAccount = xuHuang.archerAccount,
                cavalryAccount = xuHuang.cavalryAccount,
                currentPosition = xuHuang.currentPosition,
                targetPosition = xuHuang.targetPosition,
                formation = xuHuang.formation,
                activity = xuHuang.activity
            };
        }
        else if (xuChu != null && xuChu.health > 0 && xuChu.generalName == generalName)
        {
            return new GeneralInfo
            {
                generalName = xuChu.generalName,
                health = xuChu.health,
                is_attacking = xuChu.is_attacking,
                is_arrive = xuChu.is_arrive,
                infantryAccount = xuChu.infantryAccount,
                archerAccount = xuChu.archerAccount,
                cavalryAccount = xuChu.cavalryAccount,
                currentPosition = xuChu.currentPosition,
                targetPosition = xuChu.targetPosition,
                formation = xuChu.formation,
                activity = xuChu.activity
            };
        }

        // 没有找到对应将军或将军已牺牲
        return null;
    }
}